package com.example.testapp.activity.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.example.testapp.R;
import com.example.testapp.activity.fragment.HotsNewFragment;
import com.example.testapp.activity.fragment.PhoneGrilFragment;
import com.example.testapp.activity.fragment.PhoneTechFragment;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * homeActivity  业务类
 *
 * Created by l on 2016/8/25.
 */
public class HomeController {

    private static final String TAG = "HomeController";

    /**
     *一级fragment容器
     * */
    public static Fragment[] fragments;

    /**
     *  tab iv控件
     * **/
    public static ImageView[] imageViews;

    /**
     *  图片的资源id
     * **/
    public int[] imgIds = new int[]{R.raw.phone_press, R.raw.news_press, R.raw.girl_press};

    /**
     * 做标签，记录当前是哪个fragment
     * */
    public int MARK = 0;

    /**
     * 二级容器fragment的层次关系
     * **/
    public List<List<Fragment>> containerFms;

    private FragmentActivity mActivity;

    public HomeController(FragmentActivity act) {
         this.mActivity = act;
        // EventBus.getDefault().register(this);
        initFragment();
        initFoot();
    }

    /**
     *  处理下方导航item的点击事件
     * **/
    private void handlTabClick(int position) {
        FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
        Fragment  showFm;
        showFm = fragments[position];

        hideFragment(ft, fragments[MARK]);
        showFragment(showFm, ft);
        ft.commitAllowingStateLoss();

        imageViews[position].setImageResource(imgIds[position]);
        MARK = position;
    }

    /** 初始化fragment */
    private void initFragment() {
        containerFms = new ArrayList<List<Fragment>>();
        containerFms.add(new ArrayList<Fragment>());
        containerFms.add(new ArrayList<Fragment>());
        containerFms.add(new ArrayList<Fragment>());

        fragments = new Fragment[3];
        fragments[0] = new PhoneTechFragment();
        fragments[1] = new HotsNewFragment();
        fragments[2] = new PhoneGrilFragment();
        FragmentManager fm = mActivity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.home_basiceFm_containerr, fragments[0], fragments[0].getClass().getName());
        ft.add(R.id.home_basiceFm_containerr, fragments[1], fragments[1].getClass().getName());
        ft.add(R.id.home_basiceFm_containerr, fragments[2], fragments[2].getClass().getName());
        ft.hide(fragments[1]);
        ft.hide(fragments[2]);
        showFragment(fragments[0], ft);
        ft.commitAllowingStateLoss();
    }

    /** 初始化下面导航 */
    private void initFoot() {
       imageViews = new ImageView[3];
       imageViews[0] = (ImageView) mActivity.findViewById(R.id.home_phone_iv);
        imageViews[1] = (ImageView) mActivity.findViewById(R.id.home_news_iv);
        imageViews[2] = (ImageView) mActivity.findViewById(R.id.home_girl_iv);
        imageViews[0].setImageResource(R.raw.phone_press);
        imageViews[1].setImageResource(R.raw.news_normal);
        imageViews[2].setImageResource(R.raw.girl_normal);
    }

    /**
     * 重置下面导航
     * */
    private void resetTab() {
        imageViews[0].setImageResource(R.raw.phone_normal);
        imageViews[1].setImageResource(R.raw.news_normal);
        imageViews[2].setImageResource(R.raw.girl_normal);
    }

    public void tabOnClick(View v) {
        resetTab();
        switch (v.getId()){
            case R.id.home_phone_iv:
                handlTabClick(0);
                break;
            case R.id.home_news_iv:
                handlTabClick(1);
                break;
            case R.id.home_girl_iv:
                handlTabClick(2);
                break;
            default:
                break;
        }
    }

    /**
     * 隐藏fragment的统一入口 便于事件统计
     * @param transaction
     * @param fragment
     */
    private void hideFragment(FragmentTransaction transaction, Fragment fragment) {
          transaction.hide(fragment);
    }

    /**
     * 显示fragment的统一入口
     * @param fragment
     * @param transaction
     */
    private void showFragment(Fragment fragment, FragmentTransaction transaction) {
           transaction.show(fragment);
    }

    /**
     * 移除fragment的统一入口 便于事件统计
     * @param transaction
     * @param fragment
     */
    private void removeFragment(FragmentTransaction transaction, Fragment fragment) {
        transaction.remove(fragment);
    }

    /**
     * 处理软键盘事件
     * @param event
     * @return
     */
    public boolean handleKeyEvent(KeyEvent event) {
        List<Fragment> list = containerFms.get(MARK);
        int size = list.size();
        if(size == 0){
            return false;
        }
        Fragment fragment = list.get(size - 1);
        if(fragment instanceof IKeyEventStrategy){
            //自行对返回按钮事件进行处理,不交给上层处理
            boolean operatte = new KeyEventHandler((IKeyEventStrategy)fragment).operate(event);
            if(operatte){
                return true;
            }
        }
        return false;
    }

    /**
     * 回退到上一个FM
     */
    public boolean backFm() {
        List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
        int size = list.size();
        if(size == 0){
            return false;
        }
        Fragment fragment = list.get(size - 1);
        if(fragment instanceof IBackEventStrategy){
            //自行对返回按钮事件进行处理,不交给上层处理
            boolean operate = new BackEventHandler((IBackEventStrategy) fragment).operate();
            if(operate){
                return true;
            }
        }
        FragmentManager fm = mActivity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        hideFragment(ft, fragment);
        list.remove(fragment);

        size = list.size();
        if(size > 0){
            // 如果当前层次还有其他Fm,则显示顶层的FM
            Fragment fragment1 = list.get(size - 1);

            //判断是否是查询状态Fragment,是则返回底层页面
            if(fragment1 instanceof BackBan){
                ft.commitAllowingStateLoss();
                destoryFmStack();
                return true;
            }else{
                String showTag = fragment1.getClass().getName();
                Fragment showFm = fm.findFragmentByTag(showTag);
                if(showFm == null){
                    showFm = fragment1;
                    ft.add(R.id.home_fm_container, showFm, showFm.getClass().getName());
                }
                showFragment(showFm, ft);
            }
        }else {
            // 当前层次没有其他Fm
            showFragment(fragments[MARK], ft);
        }
        ft.commitAllowingStateLoss();
        return true;
    }

    /**
     * 隐藏当前的fragment层级,并显示底层fm
     */
    private void destoryFmStack() {
        FragmentManager manager = mActivity.getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        List<Fragment> list = containerFms.get(MARK);// 拿到当前页面的层次关系
        for (Fragment fm : list){
            Fragment fragment = manager.findFragmentByTag(fm.getClass().getName());
            if(fragment != null){
                hideFragment(ft, fragment);
            }
        }
        list.clear();
        showFragment(fragments[MARK], ft);
        ft.commitAllowingStateLoss();
    }

    public interface BackBan {

    }

  /**
 * 锦囊 用于实施策略,处理硬件返回按钮事件
 *
 * @author longtao.li
 *
 */
    class BackEventHandler{
      IBackEventStrategy strategy;

      public BackEventHandler(IBackEventStrategy strategy){
          this.strategy = strategy;
      }

      public boolean operate() {
          return strategy.backOperate();
      }
  }

    /**
     * 锦囊 用于实施策略,处理软键盘按钮事件
     *
     * @author longtao.li
     *
     */
    public class KeyEventHandler{
        IKeyEventStrategy strategy;

        public KeyEventHandler(IKeyEventStrategy strategy) {
            this.strategy = strategy;
        }

        public boolean operate(KeyEvent event) {
            return strategy.eventOperate(event);
        }
    }
}
